<?php


namespace App\Service\Cooperative;


use App\Constants\ErrorCode;
use App\Dao\ConfigDiscoverDao;
use App\Exception\BusinessException;
use App\Model\ConfigDiscover;
use Hyperf\Di\Annotation\Inject;

class ConfigDiscoverService extends BaseService
{
    /**
     * @Inject()
     * @var ConfigDiscoverDao
     */
    protected $configDiscoverDao;

    /**
     * @return \Hyperf\Database\Model\Builder[]|\Hyperf\Database\Model\Collection
     */
    public function index()
    {
        $list = $this->configDiscoverDao->where(['cooperative_id' => $this->user()->cooperative_id])->get();
        $data = [];
        foreach ($list as $key=>$item){
            $data['list'][] = [
                'id' => $item['id'],
                'status' => $item['status'],
                'type' => $item['type'],
                'ext' => $item['ext'],
                'rank' => $item['rank'],
                'image' => $item['image']
            ];
        }
        return $data;
    }

    /**
     * @param $id
     * @param array $data
     * @return bool
     */
    public function save($id, array $data)
    {
        if ($id) {
            /** @var ConfigDiscover $configDiscover */
            $configDiscover = $this->configDiscoverDao->first(['id' => $id, 'cooperative_id' => $this->user()->cooperative_id]);
            if (!$configDiscover) {
                throw new BusinessException(ErrorCode::COOPERATIVE_CONFIG_DISCOVER_NOT_FOUND);
            }
        } else {
            $configDiscover = new ConfigDiscover();
            $configDiscover->cooperative_id = $this->user()->cooperative_id;
        }
        $configDiscover->fill($data);

        $ret = $configDiscover->save();

        return $ret;
    }

    /**
     * @param $id
     * @return bool|null
     * @throws \Exception
     */
    public function delete($id):int
    {
        /** @var ConfigDiscover $configDiscover */
        $configDiscover = $this->configDiscoverDao->first(['id' => $id, 'cooperative_id' => $this->user()->cooperative_id]);
        if (!$configDiscover) {
            throw new BusinessException(ErrorCode::COOPERATIVE_CONFIG_DISCOVER_NOT_FOUND);
        }
        return $configDiscover->delete();
    }
}